﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows;
using MediaAssistant.Controls.About;
using MediaAssistant.Controls.AddMovie;
using MediaAssistant.Controls.Dialog;
using MediaAssistant.Controls.NightVision;
using MediaAssistant.Controls.ProfileSelector;
using MediaAssistant.Controls.SendFeedback;
using MediaAssistant.Controls.SmartDJPreferance;
using MediaAssistant.Controls.WaitScreen;
using MediaAssistant.Data;
using MediaAssistant.Helper;
using MediaAssistant.Management;
using MefBasic;
using MefBasic.Commans;
using MediaAssistant.DAL;
using MediaAssistant.DAL.Helper;
using MefBasic.Extensions;
using Microsoft.Win32;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;

namespace MediaAssistant.Controls.TopPanel
{
    [Export(typeof(TopPanelPresenter))]
    public class TopPanelPresenter:APresenter<ITopPanelView>
    {
        [ImportingConstructor]
        public TopPanelPresenter(ITopPanelView view) : base(view)
        {
            AddFilesToLibraryCommand = new DelegateCommand(ExecuteAddFilesToLibraryCommand);
            AddFolderToLibraryCommand = new DelegateCommand(ExecuteAddFolderToLibraryCommand);
            AddMovieToLibraryCommand = new DelegateCommand(ExecuteAddMovieToLibrary);
            ExitCommand = new DelegateCommand(ExecuteExitCommand);
            AboutCommand = new DelegateCommand(ExecuteAbout);
            ChangePreferanceCommand = new DelegateCommand(ExecuteChangePreferance);
            SendFeedbackCommand = new DelegateCommand(ExecuteSendFeedback);
            ChangeProfileCommand = new DelegateCommand(ExecuteChangeProfile);
            ExportMovieIdCommand = new DelegateCommand(ExecuteExportMovieId);
            NightVisionCommand = new DelegateCommand(ExecuteNightVision);
        }

        public DelegateCommand NightVisionCommand { get; set; }

        public NightVisionWindow NightVisionWindow { get; set; }

        private void ExecuteNightVision(object obj)
        {
            if(IsNightVision==false)
            {
                NightVisionWindow = Resolve<NightVisionWindow>();
                NightVisionWindow.Closed += HandleNightVisionClosed;
                NightVisionWindow.Show();
                IsNightVision = true;
            }
            else
            {
                NightVisionWindow.Close();
            }
        }

        private void HandleNightVisionClosed(object sender, EventArgs e)
        {
            NightVisionWindow = null;
            IsNightVision = false;
        }


        public bool IsNightVision
        {
            get { return (bool)GetValue(IsNightVisionProperty); }
            set { SetValue(IsNightVisionProperty, value); }
        }

        public static readonly DependencyProperty IsNightVisionProperty =
            DependencyProperty.Register("IsNightVision", typeof(bool), typeof(TopPanelPresenter), new UIPropertyMetadata(false));


        [Import]
        public WaitScreenService WaitScreenService { get; set; }
        private void ExecuteExportMovieId(object obj)
        {
            var saveFileDlg = new SaveFileDialog();
            saveFileDlg.Filter = "Text File(*.txt)|*.txt";
            if(saveFileDlg.ShowDialog()==true)
            {
                var movies = DatabaseManager.Instance.GetAllMovies().Where(m => string.IsNullOrEmpty(m.IMDBId) == false);
                var file = File.CreateText(saveFileDlg.FileName);
                WaitScreenService.Show(movies.Count(),0);
                BackgroundScannerManager.Stop();
                lock (DatabaseManager.LockObject)
                {
                    foreach (var movie in movies)
                    {
                        if (movie.Genres.Count == 0)
                        {
                            movie.UpdateLibraryInformation();
                        }
                        var jsonData = string.Format(@"{{""Title"":""{0}"",""Year"":""{1}"",""Rated"":""{2}"",""Released"":""{3}"",""Genre"":""{4}"",""Director"":""{5}"",""Writer"":""{6}"",""Actors"":""{7}"",""Plot"":""{8}"",""Poster"":""{9}"",""Runtime"":""{10}"",""imdbRating"":""{11}"",""imdbVotes"":""{12}"",""imdbID"":""{13}"",""Response"":""True""}}",
                            movie.Title, movie.Year, movie.Rated, movie.Released, GetText(movie.Genres), GetText(movie.Directors), GetText(movie.Writers), GetText(movie.Stars), movie.Plot, movie.Poster, movie.Runtime, movie.Rating, movie.Votes, movie.IMDBId);
                        file.WriteLine(jsonData);
                        WaitScreenService.AdvanceProgress();
                        Application.Current.DoEvents();
                    }    
                }
                file.Close();
                BackgroundScannerManager.Start();
                WaitScreenService.Hide();
            }
        }

        private static object GetText(IEnumerable<LibraryItem> libraryItems)
        {
            var text = string.Empty;
            foreach (var libraryItem in libraryItems)
            {
                if(text==string.Empty)
                {
                    text += libraryItem.Title;
                }
                else
                {
                    text += "," + libraryItem.Title;
                }
            }
            return text;
        }

        public DelegateCommand ExportMovieIdCommand { get; set; }

        public DelegateCommand AddMovieToLibraryCommand { get; set; }

        private void ExecuteAddMovieToLibrary(object obj)
        {
            LazyWaitScreenPresenter.Value.Show();
            BackgroundScannerManager.Pause();
            LazyWaitScreenPresenter.Value.Hide();
            Resolve<AddMoviePresenter>().ShowAddMovie();
            BackgroundScannerManager.Resume();
        }

        public DelegateCommand ChangeProfileCommand { get; set; }
        [Import]
        private MediaFileScanner MediaFileScanner { get; set; }
        private void ExecuteChangeProfile(object obj)
        {
            LazyWaitScreenPresenter.Value.Show();
            MediaFileScanner.Stop();
            LazyWaitScreenPresenter.Value.Hide();
            if(Resolve<ProfileSelectorPresenter>().ChangeProfile())
            {
                MediaFileScanner.Start();
                DataSource.RefreshResult();    
            }
        }

        public DelegateCommand SendFeedbackCommand { get; set; }

        private void ExecuteSendFeedback(object obj)
        {
            Resolve<SendFeedbackPresenter>().SendFeedback();
        }

        public DelegateCommand ChangePreferanceCommand { get; set; }

        private void ExecuteChangePreferance(object obj)
        {
            var preferancePresenter = Resolve<SmartDJPreferancePresenter>();
            if(Resolve<IDialogPresenter>().ShowDialog("Preferance",preferancePresenter)==DialogResult.Ok)
            {
                RegistryHelper.ArtistPreferance = preferancePresenter.ArtistPreferance;
                RegistryHelper.AlbumPreferance = preferancePresenter.AlbumPreferance;
                RegistryHelper.ComposerPreferance = preferancePresenter.ComposerPreferance;
                RegistryHelper.GenrePreferance = preferancePresenter.GenrePreferance;
            }
        }

        public DelegateCommand AboutCommand { get; set; }

        private void ExecuteAbout(object obj)
        {
            Resolve<AboutPresenter>().ShowDialog();
        }

        public DelegateCommand ExitCommand { get; set; }

        private static void ExecuteExitCommand(object obj)
        {
            Application.Current.Shutdown();
        }

        [Import]
        private Lazy<WaitScreenPresenter> LazyWaitScreenPresenter { get; set; }
        public DelegateCommand AddFolderToLibraryCommand { get; set; }
        private void ExecuteAddFolderToLibraryCommand(object obj)
        {
            var folderPath = SystemHelper.GetFolderPath(RegistryHelper.LastAddedFolderLocation);

            if(folderPath==null)
                return;
            
            RegistryHelper.LastAddedFolderLocation = folderPath;
            LazyWaitScreenPresenter.Value.Show();
            BackgroundScannerManager.Pause();
            DatabaseManager.Instance.ClearLastImportedPlaylist();
            DataSource.AddFolderInBackground(folderPath);
            //DataSource.SelectLastImportedPlaylist();
            BackgroundScannerManager.Resume();
            LazyWaitScreenPresenter.Value.Hide();
        }

        [Import]
        public LibraryDataSource DataSource { get; set; }

        [Import]
        private BackgroundScannerManager BackgroundScannerManager { get; set; }

        public DelegateCommand AddFilesToLibraryCommand { get; set; }

        private void ExecuteAddFilesToLibraryCommand(object obj)
        {
            var fileDialog = new OpenFileDialog {Filter = Utility.SupportedFileFilter, Multiselect = true};
            if(fileDialog.ShowDialog()==true)
            {
                LazyWaitScreenPresenter.Value.Show();
                BackgroundScannerManager.Pause();
                DatabaseManager.Instance.ClearLastImportedPlaylist();
                DataSource.AddFilesInBackground(fileDialog.FileNames);
                DataSource.SelectLastImportedPlaylist();
                BackgroundScannerManager.Resume();
                LazyWaitScreenPresenter.Value.Hide();
            }
        }


        [Import]
        public LibraryManager LibraryManager
        {
            get { return (LibraryManager)GetValue(LibraryManagerProperty); }
            set { SetValue(LibraryManagerProperty, value); }
        }

        public static readonly DependencyProperty LibraryManagerProperty =
            DependencyProperty.Register("LibraryManager", typeof(LibraryManager), typeof(TopPanelPresenter), new UIPropertyMetadata(null));

    }
}
